package com.fetch.ui;

import java.awt.Color;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;

/**
 * 日志面板
 *
 */
public class LogPane extends JTextPane {
	
	private static final long serialVersionUID = 1L;
	
	private final int buffSize = 50000; //日志缓存字符数
	private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	/**
	 * 一般信息
	 * @param msg
	 */
	public void info(String msg){
		log(msg, Color.BLACK);
	}
	
	/**
	 * 警告
	 * @param msg
	 */
	public void warn(String msg){
		log(msg, Color.ORANGE);
	}
	
	/**
	 * 错误
	 * @param msg
	 */
	public void error(String msg){
		log(msg, Color.RED);
	}
	
	private void log(String msg, Color textColor){
		insertDocument(format.format(new Date()) + "  " + msg + "\n", textColor);
	}
	
	public void insertDocument(String text, Color textColor){
		SimpleAttributeSet set = new SimpleAttributeSet();
		StyleConstants.setForeground(set, textColor);
		StyleConstants.setFontSize(set, 12);
		Document doc = this.getStyledDocument();
		try {
			doc.insertString(0, text, set);
		} catch (BadLocationException e) {
			e.printStackTrace();
		}
		if(doc.getLength() > buffSize){
			try {
				doc.remove(buffSize, doc.getLength()-buffSize);
			} catch (BadLocationException e) {
				e.printStackTrace();
			}
		}
	}
}
